package com.mck.service.impl;

import com.mck.anno.OperationLog;
import com.mck.entity.Score;
import com.mck.entity.ScoreStats;
import com.mck.entity.ScoreTotal;
import com.mck.mapper.ScoreMapper;
import com.mck.mapper.ScoreStatsMapper;
import com.mck.mapper.ScoreTotalMapper;
import com.mck.service.ScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Max
 * @Date 2025/3/11 上午1:12
 */
@Service
@Slf4j
public class ScoreServiceImpl implements ScoreService {

    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private ScoreStatsMapper scoreStatsMapper;
    @Autowired
    private ScoreTotalMapper scoreTotalMapper;

    // 获取成绩列表
    @Override
    @Cacheable(value = "scoreList", key = "'all'", unless = "#result.isEmpty()")
    public List<Score> getScoreList() {
        return scoreMapper.getScoreList();
    }

    // 获取指定成绩列表
    @Override
    @Cacheable(value = "specificScore", key = "#score", unless = "#result.isEmpty()")
    public List<Score> getScoreListBySpecific(Score score) {
        return scoreMapper.getScoreListBySpecific(score);
    }

    // 添加成绩列表
    // @OperationLog
    // @Override
    // @Transactional
    // @Caching(evict = {@CacheEvict(value = "scoreList", key = "'all'"),  // 清理全部列表缓存
    //         @CacheEvict(value = "specificScore", allEntries = true)  // 清理所有条件查询缓存
    // })
    // public void addScoreList(List<Score> scoreList) {
    //     final LocalDateTime now = LocalDateTime.now();
    //     if (scoreList == null || scoreList.isEmpty()) return;

//         // 初始化统计参数
//         float totalTheory = 0;
//         float totalPractice = 0;
//         int excellentCountTheory = 0;
//         int passCountTheory = 0;
//         int excellentCountPractice = 0;
//         int passCountPractice = 0;
//         float maxTheory = Float.NEGATIVE_INFINITY;
//         float maxPractice = Float.NEGATIVE_INFINITY;
//         int theoryTotalViolations = 0;
//         int theoryTotalAbsences = 0;
//         List<String> theoryViolationStudentIds = new ArrayList<>();
//         List<String> topTheoryStudentIds = new ArrayList<>();
//         int practiceTotalViolations = 0;
//         int practiceTotalAbsences = 0;
//         List<String> practiceViolationStudentIds = new ArrayList<>();
//         List<String> topPracticeStudentIds = new ArrayList<>();
//
//         // 遍历计算统计值
//         for (Score score : scoreList) {
//             // 获取分数值
//             float theory = score.getTheoryTotal();
//             float practice = score.getPracticeTotal();
//             Integer studentId = score.getStudentId();
//
//             // 理论分统计
//             totalTheory += theory;
//             if (theory > 80) {
//                 excellentCountTheory++;
//                 passCountTheory++;
//             } else if (theory > 60) {
//                 passCountTheory++;
//             }
//
//             // 理论缺考判断
//             if ("absent".equals(score.getAboutTheory())) {
//                 theoryTotalAbsences++;
//             }
//
//             // 理论违规处理
//             if (score.getAboutTheory() != null && "violation".equals(score.getAboutTheory())) {
//                 theoryTotalViolations++;
//                 theoryViolationStudentIds.add(String.valueOf(studentId));
//             }
//
//             // 理论最高分处理
//             if (theory > maxTheory) {
//                 maxTheory = theory;
//                 topTheoryStudentIds.clear();
//                 topTheoryStudentIds.add(String.valueOf(studentId));
//             } else if (theory == maxTheory) {
//                 topTheoryStudentIds.add(String.valueOf(studentId));
//             }
//
//             // 实践分统计
//             totalPractice += practice;
//             if (practice > 80) {
//                 excellentCountPractice++;
//                 passCountPractice++;
//             } else if (practice > 60) {
//                 passCountPractice++;
//             }
//
//             // 实践缺考判断
//             if ("absent".equals(score.getAboutPractice())) {
//                 practiceTotalAbsences++;
//             }
//
//             // 实践违规处理
//             if (score.getAboutPractice() != null && "violation".equals(score.getAboutPractice())) {
//                 practiceTotalViolations++;
//                 practiceViolationStudentIds.add(String.valueOf(studentId));
//             }
//
//             // 实践最高分处理
//             if (practice > maxPractice) {
//                 maxPractice = practice;
//                 topPracticeStudentIds.clear();
//                 topPracticeStudentIds.add(String.valueOf(studentId));
//             } else if (practice == maxPractice) {
//                 topPracticeStudentIds.add(String.valueOf(studentId));
//             }
//         }
//
//         // 计算总分
//         String academicYear = scoreList.getFirst().getAcademicYear();
//         Integer classId = scoreList.getFirst().getClassId();
//
//         Set<Integer> studentIds = scoreList.stream()
//                 .map(Score::getStudentId)
//                 .collect(Collectors.toSet());
//
//         List<ScoreTotal> totals = new ArrayList<>();
//         for (Integer studentId : studentIds) {
//             ScoreTotal param = new ScoreTotal();
//             param.setAcademyYear(scoreList.getFirst().getAcademicYear());
//             param.setClassId(scoreList.getFirst().getClassId());
//             param.setUserId(studentId);
//             totals.addAll(scoreTotalMapper.computeScoreTotal(param));
//         }
//
//         log.info("计算得到的总分数据: {}", totals);
//         // 设置更新时间并执行批量操作
//         totals.forEach(t -> t.setUpdateTime(now));
//         if (!totals.isEmpty()) {
//             scoreTotalMapper.batchUpsertScoreTotal(totals);
//         }
//
//         int count = scoreList.size();
//         // 计算优秀率、及格率（保留两位小数）
//         Float excellentRateTheory = (float) (Math.round(excellentCountTheory * 100.0 / count * 100) / 100.0);
//         Float passRateTheory = (float) (Math.round(passCountTheory * 100.0 / count * 100) / 100.0);
//         Float excellentRatePractice = (float) (Math.round(excellentCountPractice * 100.0 / count * 100) / 100.0);
//         Float passRatePractice = (float) (Math.round(passCountPractice * 100.0 / count * 100) / 100.0);
//
//
//         // 计算平均值（保留两位小数）
//         Float avgScoreTheory = (float) (Math.round(totalTheory / count * 100) / 100.0);
//         Float avgScorePractice = (float) (Math.round(totalPractice / count * 100) / 100.0);
//
//         // 处理全缺考场景
//         maxTheory = maxTheory == Float.NEGATIVE_INFINITY ? 0 : maxTheory;
//         maxPractice = maxPractice == Float.NEGATIVE_INFINITY ? 0 : maxPractice;
//
//         // 构建参数对象
//         String academyYear = scoreList.getFirst().getAcademicYear();
//         // Integer classId = scoreList.getFirst().getClassId();
//         Integer subjectId = scoreList.getFirst().getSubjectId();
//         ScoreStats scoreStatsParam = new ScoreStats();
//         scoreStatsParam.setAcademyYear(academyYear);
//         scoreStatsParam.setClassId(classId);
//         scoreStatsParam.setSubjectId(subjectId);
//
//         // 获取已有统计记录
//         List<ScoreStats> statsList = scoreStatsMapper.getScoreStatsList(scoreStatsParam);
//
//         // 构建完整统计对象
//         ScoreStats newScoreStats = new ScoreStats();
//         newScoreStats.setAcademyYear(academyYear);
//         newScoreStats.setClassId(classId);
//         newScoreStats.setSubjectId(subjectId);
//         newScoreStats.setExcellentRateTheory(excellentRateTheory);
//         newScoreStats.setPassRateTheory(passRateTheory);
//         newScoreStats.setAvgScoreTheory(avgScoreTheory);
//         newScoreStats.setMaxScoreTheory(maxTheory);
//         newScoreStats.setUpdateTimeTheory(now);
//         newScoreStats.setExcellentRatePractice(excellentRatePractice);
//         newScoreStats.setPassRatePractice(passRatePractice);
//         newScoreStats.setAvgScorePractice(avgScorePractice);
//         newScoreStats.setMaxScorePractice(maxPractice);
//         newScoreStats.setUpdateTimePractice(now);
//
//         // 设置新增统计字段
//         newScoreStats.setTheoryTotalViolations(theoryTotalViolations);
//         newScoreStats.setTheoryTotalAbsences(theoryTotalAbsences);
//         newScoreStats.setTheoryViolationStudentIds(theoryViolationStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setTopTheoryStudentIds(topTheoryStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setPracticeTotalViolations(practiceTotalViolations);
//         newScoreStats.setPracticeTotalAbsences(practiceTotalAbsences);
//         newScoreStats.setPracticeViolationStudentIds(practiceViolationStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setTopPracticeStudentIds(topPracticeStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//
//         // 更新或插入统计记录
//         if (statsList.isEmpty()) {
//             scoreStatsMapper.addScoreStats(newScoreStats);
//         } else {
//             scoreStatsMapper.updateScoreStats(newScoreStats);
//         }
//
//         // 处理成绩数据
//         List<Score> existScores = scoreMapper.getExistScores(scoreList);
//         List<Score> insertList = new ArrayList<>();
//         List<Score> updateList = new ArrayList<>();
//
//         for (Score score : scoreList) {
//             score.setCreateTime(now);
//             boolean exists = existScores.stream().anyMatch(s -> s.getStudentId().equals(score.getStudentId()) && s.getSubjectId().equals(score.getSubjectId()) && s.getAcademicYear().equals(score.getAcademicYear()));
//             (exists ? updateList : insertList).add(score);
//         }
//
//         // 批量操作
//         if (!insertList.isEmpty()) scoreMapper.batchInsertScore(insertList);
//         if (!updateList.isEmpty()) scoreMapper.batchUpdateScore(updateList);
//     }
// }


//     // 添加成绩列表
//     @OperationLog
//     @Override
//     @Transactional
//     @Caching(evict = {@CacheEvict(value = "scoreList", key = "'all'"), @CacheEvict(value = "specificScore", allEntries = true)})
//     public void addScoreList(List<Score> scoreList) {
//         log.info("输入的成绩数据： {}", scoreList);
//
//         final LocalDateTime now = LocalDateTime.now();
//         if (scoreList == null || scoreList.isEmpty()) return;
//
//         // 初始化统计参数
//         float totalTheory = 0;
//         float totalPractice = 0;
//         int theoryCount = 0;
//         int practiceCount = 0;
//         int excellentCountTheory = 0;
//         int passCountTheory = 0;
//         int excellentCountPractice = 0;
//         int passCountPractice = 0;
//         float maxTheory = Float.NEGATIVE_INFINITY;
//         float maxPractice = Float.NEGATIVE_INFINITY;
//         int theoryTotalViolations = 0;
//         int theoryTotalAbsences = 0;
//         List<String> theoryViolationStudentIds = new ArrayList<>();
//         List<String> topTheoryStudentIds = new ArrayList<>();
//         int practiceTotalViolations = 0;
//         int practiceTotalAbsences = 0;
//         List<String> practiceViolationStudentIds = new ArrayList<>();
//         List<String> topPracticeStudentIds = new ArrayList<>();
//
//         // 遍历计算统计值
//         for (Score score : scoreList) {
//             Integer studentId = score.getStudentId();
//             Float theory = score.getTheoryTotal();
//             Float practice = score.getPracticeTotal();
//
//             // 理论分统计
//             if (theory != null) {
//                 theoryCount++;
//                 totalTheory += theory;
//
//                 if (theory >= 80) {
//                     excellentCountTheory++;
//                     passCountTheory++;
//                 } else if (theory >= 60) {
//                     passCountTheory++;
//                 }
//
//                 // 理论最高分处理
//                 if (theory > maxTheory) {
//                     maxTheory = theory;
//                     topTheoryStudentIds.clear();
//                     topTheoryStudentIds.add(studentId.toString());
//                 } else if (theory == maxTheory) {
//                     topTheoryStudentIds.add(studentId.toString());
//                 }
//             }
//
//             // 理论缺考判断
//             if ("absent".equals(score.getAboutTheory())) {
//                 theoryTotalAbsences++;
//             }
//
//             // 理论违规处理
//             if (score.getAboutTheory() != null && "violation".equals(score.getAboutTheory())) {
//                 theoryTotalViolations++;
//                 theoryViolationStudentIds.add(studentId.toString());
//             }
//
//             // 实践分统计
//             if (practice != null) {
//                 practiceCount++;
//                 totalPractice += practice;
//
//                 if (practice >= 80) {
//                     excellentCountPractice++;
//                     passCountPractice++;
//                 } else if (practice >= 60) {
//                     passCountPractice++;
//                 }
//
//                 // 实践最高分处理
//                 if (practice > maxPractice) {
//                     maxPractice = practice;
//                     topPracticeStudentIds.clear();
//                     topPracticeStudentIds.add(studentId.toString());
//                 } else if (practice == maxPractice) {
//                     topPracticeStudentIds.add(studentId.toString());
//                 }
//             }
//
//             // 实践缺考判断
//             if ("absent".equals(score.getAboutPractice())) {
//                 practiceTotalAbsences++;
//             }
//
//             // 实践违规处理
//             if (score.getAboutPractice() != null && "violation".equals(score.getAboutPractice())) {
//                 practiceTotalViolations++;
//                 practiceViolationStudentIds.add(studentId.toString());
//             }
//         }
//
//         // 计算总分
//         String academicYear = scoreList.getFirst().getAcademicYear();
//         Integer classId = scoreList.getFirst().getClassId();
//
//         Set<Integer> studentIds = scoreList.stream().map(Score::getStudentId).collect(Collectors.toSet());
//
//         List<ScoreTotal> totals = new ArrayList<>();
//         for (Integer studentId : studentIds) {
//             ScoreTotal param = new ScoreTotal();
//             param.setAcademyYear(scoreList.getFirst().getAcademicYear());
//             param.setClassId(scoreList.getFirst().getClassId());
//             param.setUserId(studentId);
//             totals.addAll(scoreTotalMapper.computeScoreTotal(param));
//         }
//
//         log.info("计算得到的总分数据: {}", totals);
//         // 设置更新时间并执行批量操作
//         totals.forEach(t -> t.setUpdateTime(now));
//         if (!totals.isEmpty()) {
//             scoreTotalMapper.batchUpsertScoreTotal(totals);
//         }
//
//         int count = scoreList.size();
//
//         // 计算优秀率、及格率、平均值
//         Float excellentRateTheory = 0f;
//         Float passRateTheory = 0f;
//         Float avgScoreTheory = 0f;
//         if (theoryCount > 0) {
//             excellentRateTheory = Math.round(excellentCountTheory * 10000.0f / theoryCount) / 100.0f;
//             passRateTheory = Math.round(passCountTheory * 10000.0f / theoryCount) / 100.0f;
//             avgScoreTheory = Math.round(totalTheory / theoryCount * 100) / 100.0f;
//         }
//
//         Float excellentRatePractice = 0f;
//         Float passRatePractice = 0f;
//         Float avgScorePractice = 0f;
//         if (practiceCount > 0) {
//             excellentRatePractice = Math.round(excellentCountPractice * 10000.0f / practiceCount) / 100.0f;
//             passRatePractice = Math.round(passCountPractice * 10000.0f / practiceCount) / 100.0f;
//             avgScorePractice = Math.round(totalPractice / practiceCount * 100) / 100.0f;
//         }
//
//         // 处理全缺考场景
//         maxTheory = maxTheory == Float.NEGATIVE_INFINITY ? 0 : maxTheory;
//         maxPractice = maxPractice == Float.NEGATIVE_INFINITY ? 0 : maxPractice;
//
//         // 构建参数对象
//         String academyYear = scoreList.getFirst().getAcademicYear();
//         // Integer classId = scoreList.getFirst().getClassId();
//         Integer subjectId = scoreList.getFirst().getSubjectId();
//         ScoreStats scoreStatsParam = new ScoreStats();
//         scoreStatsParam.setAcademyYear(academyYear);
//         scoreStatsParam.setClassId(classId);
//         scoreStatsParam.setSubjectId(subjectId);
//
//         // 获取已有统计记录
//         List<ScoreStats> statsList = scoreStatsMapper.getScoreStatsList(scoreStatsParam);
//
//         // 在构建统计对象前添加日志
//         log.info("理论统计: 优秀率={}, 及格率={}, 平均分={}, 最高分={}", excellentRateTheory, passRateTheory, avgScoreTheory, maxTheory);
//         log.info("实践统计: 优秀率={}, 及格率={}, 平均分={}, 最高分={}", excellentRatePractice, passRatePractice, avgScorePractice, maxPractice);
//
// // // 更新或插入统计记录前添加日志
// //         log.info("统计记录是否存在: {}", !statsList.isEmpty());
// //         if (statsList.isEmpty()) {
// //             scoreStatsMapper.addScoreStats(newScoreStats);
// //             log.info("插入新统计记录: {}", newScoreStats);
// //         } else {
// //             scoreStatsMapper.updateScoreStats(newScoreStats);
// //             log.info("更新统计记录: {}", newScoreStats);
// //         }
//
//         // 构建完整统计对象
//         ScoreStats newScoreStats = new ScoreStats();
//         newScoreStats.setAcademyYear(academyYear);
//         newScoreStats.setClassId(classId);
//         newScoreStats.setSubjectId(subjectId);
//         newScoreStats.setExcellentRateTheory(excellentRateTheory);
//         newScoreStats.setPassRateTheory(passRateTheory);
//         newScoreStats.setAvgScoreTheory(avgScoreTheory);
//         newScoreStats.setMaxScoreTheory(maxTheory);
//         newScoreStats.setUpdateTimeTheory(now);
//         newScoreStats.setExcellentRatePractice(excellentRatePractice);
//         newScoreStats.setPassRatePractice(passRatePractice);
//         newScoreStats.setAvgScorePractice(avgScorePractice);
//         newScoreStats.setMaxScorePractice(maxPractice);
//         newScoreStats.setUpdateTimePractice(now);
//
//         // 设置新增统计字段
//         newScoreStats.setTheoryTotalViolations(theoryTotalViolations);
//         newScoreStats.setTheoryTotalAbsences(theoryTotalAbsences);
//         newScoreStats.setTheoryViolationStudentIds(theoryViolationStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setTopTheoryStudentIds(topTheoryStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setPracticeTotalViolations(practiceTotalViolations);
//         newScoreStats.setPracticeTotalAbsences(practiceTotalAbsences);
//         newScoreStats.setPracticeViolationStudentIds(practiceViolationStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//         newScoreStats.setTopPracticeStudentIds(topPracticeStudentIds.stream().map(Object::toString).collect(Collectors.joining(",")));
//
//         // 更新或插入统计记录
//         log.info("统计记录是否存在: {}", !statsList.isEmpty());
//         if (statsList.isEmpty()) {
//             scoreStatsMapper.addScoreStats(newScoreStats);
//             log.info("插入新统计记录: {}", newScoreStats);
//
//         } else {
//             scoreStatsMapper.updateScoreStats(newScoreStats);
//             log.info("更新统计记录: {}", newScoreStats);
//
//         }
//
//         // 处理成绩数据
//         List<Score> existScores = scoreMapper.getExistScores(scoreList);
//         List<Score> insertList = new ArrayList<>();
//         List<Score> updateList = new ArrayList<>();
//
//         for (Score score : scoreList) {
//             score.setCreateTime(now);
//             boolean exists = existScores.stream().anyMatch(s -> s.getStudentId().equals(score.getStudentId()) && s.getSubjectId().equals(score.getSubjectId()) && s.getAcademicYear().equals(score.getAcademicYear()));
//             (exists ? updateList : insertList).add(score);
//         }
//
//         // 批量操作
//         if (!insertList.isEmpty()) scoreMapper.batchInsertScore(insertList);
//         if (!updateList.isEmpty()) scoreMapper.batchUpdateScore(updateList);
//     }
// }


    @OperationLog
    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = "scoreList", key = "'all'"), @CacheEvict(value = "specificScore", allEntries = true)})
    public void addScoreList(List<Score> scoreList) {
        // log.info("输入的成绩数据：{}", scoreList);
        final LocalDateTime now = LocalDateTime.now();
        if (scoreList == null || scoreList.isEmpty()) return;

        // 按学科统计
        // 1. 按学科分组
        Map<Integer, List<Score>> scoresBySubject = scoreList.stream().collect(Collectors.groupingBy(Score::getSubjectId));

        // 2. 遍历每个学科，计算统计信息
        scoresBySubject.forEach((subjectId, subjectScores) -> {
            // 初始化统计参数（每个学科独立）
            float totalTheory = 0;
            float totalPractice = 0;
            int theoryCount = 0;
            int practiceCount = 0;
            int excellentCountTheory = 0;
            int passCountTheory = 0;
            int excellentCountPractice = 0;
            int passCountPractice = 0;
            float maxTheory = Float.NEGATIVE_INFINITY;
            float maxPractice = Float.NEGATIVE_INFINITY;
            int theoryTotalViolations = 0;
            int theoryTotalAbsences = 0;
            List<String> theoryViolationStudentIds = new ArrayList<>();
            List<String> topTheoryStudentIds = new ArrayList<>();
            int practiceTotalViolations = 0;
            int practiceTotalAbsences = 0;
            List<String> practiceViolationStudentIds = new ArrayList<>();
            List<String> topPracticeStudentIds = new ArrayList<>();

            // 遍历当前学科的成绩
            for (Score score : subjectScores) {
                Integer studentId = score.getStudentId();
                Float theory = score.getTheoryTotal();
                Float practice = score.getPracticeTotal();

                // 理论分统计
                if (theory != null) {
                    theoryCount++;
                    totalTheory += theory;
                    if (theory >= 80) {
                        excellentCountTheory++;
                        passCountTheory++;
                    } else if (theory >= 60) {
                        passCountTheory++;
                    }
                    // 最高分处理
                    if (theory > maxTheory) {
                        maxTheory = theory;
                        topTheoryStudentIds.clear();
                        topTheoryStudentIds.add(studentId.toString());
                    } else if (theory == maxTheory) {
                        topTheoryStudentIds.add(studentId.toString());
                    }
                }

                // 实践分统计
                if (practice != null) {
                    practiceCount++;
                    totalPractice += practice;
                    if (practice >= 80) {
                        excellentCountPractice++;
                        passCountPractice++;
                    } else if (practice >= 60) {
                        passCountPractice++;
                    }
                    // 最高分处理
                    if (practice > maxPractice) {
                        maxPractice = practice;
                        topPracticeStudentIds.clear();
                        topPracticeStudentIds.add(studentId.toString());
                    } else if (practice == maxPractice) {
                        topPracticeStudentIds.add(studentId.toString());
                    }
                }

                // 缺考统计
                if ("absent".equals(score.getAboutTheory())) theoryTotalAbsences++;
                if ("absent".equals(score.getAboutPractice())) practiceTotalAbsences++;

                // 违规统计
                if ("violation".equals(score.getAboutTheory())) {
                    theoryTotalViolations++;
                    theoryViolationStudentIds.add(studentId.toString());
                }
                if ("violation".equals(score.getAboutPractice())) {
                    practiceTotalViolations++;
                    practiceViolationStudentIds.add(studentId.toString());
                }
            }

            // 计算统计值
            int totalStudents = subjectScores.size(); // 获取总人数

            Float excellentRateTheory = calculateRate(excellentCountTheory, totalStudents);
            Float passRateTheory = calculateRate(passCountTheory, totalStudents);
            Float avgScoreTheory = calculateAverage(totalTheory, totalStudents);

            Float excellentRatePractice = calculateRate(excellentCountPractice, totalStudents);
            Float passRatePractice = calculateRate(passCountPractice, totalStudents);
            Float avgScorePractice = calculateAverage(totalPractice, totalStudents);

            // 处理全缺考场景
            maxTheory = (maxTheory == Float.NEGATIVE_INFINITY) ? 0 : maxTheory;
            maxPractice = (maxPractice == Float.NEGATIVE_INFINITY) ? 0 : maxPractice;

            // 构建学科统计对象
            ScoreStats newScoreStats = new ScoreStats();
            newScoreStats.setAcademyYear(subjectScores.getFirst().getAcademicYear());
            newScoreStats.setClassId(subjectScores.getFirst().getClassId());
            newScoreStats.setSubjectId(subjectId);
            newScoreStats.setExcellentRateTheory(excellentRateTheory);
            newScoreStats.setPassRateTheory(passRateTheory);
            newScoreStats.setAvgScoreTheory(avgScoreTheory);
            newScoreStats.setMaxScoreTheory(maxTheory);
            newScoreStats.setUpdateTimeTheory(now);
            newScoreStats.setExcellentRatePractice(excellentRatePractice);
            newScoreStats.setPassRatePractice(passRatePractice);
            newScoreStats.setAvgScorePractice(avgScorePractice);
            newScoreStats.setMaxScorePractice(maxPractice);
            newScoreStats.setUpdateTimePractice(now);
            newScoreStats.setTheoryTotalViolations(theoryTotalViolations);
            newScoreStats.setTheoryTotalAbsences(theoryTotalAbsences);
            newScoreStats.setTheoryViolationStudentIds(String.join(",", theoryViolationStudentIds));
            newScoreStats.setTopTheoryStudentIds(String.join(",", topTheoryStudentIds));
            newScoreStats.setPracticeTotalViolations(practiceTotalViolations);
            newScoreStats.setPracticeTotalAbsences(practiceTotalAbsences);
            newScoreStats.setPracticeViolationStudentIds(String.join(",", practiceViolationStudentIds));
            newScoreStats.setTopPracticeStudentIds(String.join(",", topPracticeStudentIds));

            // 更新或插入学科统计
            ScoreStats param = new ScoreStats();
            param.setAcademyYear(newScoreStats.getAcademyYear());
            param.setClassId(newScoreStats.getClassId());
            param.setSubjectId(newScoreStats.getSubjectId());
            List<ScoreStats> statsList = scoreStatsMapper.getScoreStatsList(param);

            if (statsList.isEmpty()) {
                scoreStatsMapper.addScoreStats(newScoreStats);
                log.info("插入学科统计记录: {}", newScoreStats);
            } else {
                scoreStatsMapper.updateScoreStats(newScoreStats);
                log.info("更新学科统计记录: {}", newScoreStats);
            }
        });

        // 学生总分统计
        // 1. 按学生分组，计算总分
        Map<Integer, List<Score>> scoresByStudent = scoreList.stream().collect(Collectors.groupingBy(Score::getStudentId));

        List<ScoreTotal> totals = new ArrayList<>();
        scoresByStudent.forEach((studentId, studentScores) -> {
            // 计算总分
            Float theoryTotal = studentScores.stream().map(Score::getTheoryTotal).filter(Objects::nonNull).reduce(0f, Float::sum);

            Float practiceTotal = studentScores.stream().map(Score::getPracticeTotal).filter(Objects::nonNull).reduce(0f, Float::sum);

            // 构建总分对象
            ScoreTotal total = new ScoreTotal();
            total.setUserId(studentId);
            total.setAcademyYear(scoreList.getFirst().getAcademicYear());
            total.setClassId(scoreList.getFirst().getClassId());
            total.setTheoryTotal(theoryTotal);
            total.setPracticeTotal(practiceTotal);
            total.setUpdateTime(now);
            totals.add(total);
        });

        // 2. 批量更新总分
        if (!totals.isEmpty()) {
            scoreTotalMapper.batchUpsertScoreTotal(totals);
            log.info("更新总分数据: {}", totals);
        }

        // 处理成绩
        List<Score> existScores = scoreMapper.getExistScores(scoreList);
        List<Score> insertList = new ArrayList<>();
        List<Score> updateList = new ArrayList<>();

        for (Score score : scoreList) {
            score.setCreateTime(now);
            boolean exists = existScores.stream().anyMatch(s -> s.getStudentId().equals(score.getStudentId()) && s.getSubjectId().equals(score.getSubjectId()) && s.getAcademicYear().equals(score.getAcademicYear()));
            (exists ? updateList : insertList).add(score);
        }

        if (!insertList.isEmpty()) {
            scoreMapper.batchInsertScore(insertList);
            log.info("批量插入成绩: {}", insertList.size());
        }
        if (!updateList.isEmpty()) {
            scoreMapper.batchUpdateScore(updateList);
            log.info("批量更新成绩: {}", updateList.size());
        }
    }

    // 辅助方法：计算比率
    private Float calculateRate(int numerator, int denominator) {
        return denominator > 0 ? Math.round(numerator * 10000.0f / denominator) / 100.0f : 0f;
    }

    // 辅助方法：计算平均分
    private Float calculateAverage(float total, int count) {
        return count > 0 ? Math.round(total / count * 100) / 100.0f : 0f;
    }
}